package com.example.filter;

import com.example.model.Key;
import com.example.util.RSAUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 *  验证签名的过滤器
 */
public class VerifyFilter implements Filter {
    @Override
    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletResponse response = (HttpServletResponse) resp;
        HttpServletRequest request = (HttpServletRequest) req;
        String xSid = request.getHeader("X-SID");
        String xSignature = request.getHeader("X-Signature");
        boolean verify = false;
        try {
            verify = RSAUtil.verify(xSid, xSignature, RSAUtil.string2PublicKey(Key.publicKey));
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (verify) {
            chain.doFilter(req, resp);
        } else {
            // 验签失败则返回403
            response.setStatus(403);
        }

    }

    @Override
    public void init(FilterConfig config) throws ServletException {

    }

}
